layui.define(['layer','form','table','laytpl','element'], function(exports){
    var layer = layui.layer,form=layui.form,table=layui.table,laytpl=layui.laytpl,element=layui.element;
    var mftUtil = {
        data:{mftBills:[], mftGoods:[],mftContainers:[]},
        renderBills:function (reset) {
            if(reset){$.each(mftUtil.data.mftBills,function (i,o) {o['LAY_CHECKED'] = false;o['LAY_TABLE_INDEX'] = i;o['listNo'] = (i+1);});}
            table.render({
                elem: '#mft-bill-list', id: 'mft-bill-list', limit: 500, page: false,  height:140,text:{none:'暂无数据'},
                cols:[[
                    {type: 'checkbox',width:35}
                    ,{field:'listNo',title:'序号',width:40,align:'center'}
                    ,{field:'billNo',title:'提(运)单号'}
                    ,{field:'goodsCustomsStat',title:'货物通关名称'}
                    ,{field:'packNum',title:'货物总件数'}
                    ,{field:'grossWt',title:'货物总毛重(KG)'}
                    ,{field:'consigneeName',title:'收货人名称'}
                    ,{field:'consignorName',title:'发货人名称'}
                ]]
                ,data:mftUtil.data.mftBills
            });
        },
        renderGoods:function(){
            var newMftGoods = [],billNo = $('#billNo').val();
            if(isNotEmpty(billNo)){$.each(mftUtil.data.mftGoods,function (i,o) {if(o.billNo==billNo){newMftGoods.push(o);}});}
            table.render({
                elem: '#mft-good-list', id: 'mft-good-list', limit: 500, page: false,  height:140,text:{none:'无匹配数据'},
                cols:[[
                    {type: 'checkbox',width:35}
                    ,{type:'numbers',title:'序号',width:40,align:'center'}
                    ,{type:'numbers',title:'商品项序号',width:160}
                    ,{field:'goodsPackNum',title:'商品项件数'}
                    ,{field:'goodsPackType',title:'包装种类'}
                    ,{field:'goodsBriefDesc',title:'商品项简要描述'}
                    ,{field:'goodsGrossWt',title:'商品项毛重(kg)'}
                ]]
                ,data:newMftGoods
            });
        },
        renderContainers:function(){
            var newMftContainers = [],billNo = $('#billNo').val();
            if(isNotEmpty(billNo)){$.each(mftUtil.data.mftContainers,function (i,o) {if(o.billNo==billNo){newMftContainers.push(o);}});}
            table.render({
                elem: '#mft-container-list', id: 'mft-container-list', limit: 500, page: false,  height:140,text:{none:'无匹配数据'},
                cols:[[
                    {type: 'checkbox',width:35}
                    ,{type:'numbers',title:'序号',width:40,align:'center'}
                    ,{field:'contaId',title:'集装箱(器)编号'}
                    ,{field:'contaSizeType',title:'尺寸和类型'}
                    ,{field:'contaSuppId',title:'来源代码'}
                    ,{field:'contaLoadedType',title:'重箱或空箱标识'}
                ]]
                ,data:newMftContainers
            });
        },
        init:function () {
            mftUtil.renderBills();
            mftUtil.renderGoods();
            mftUtil.renderContainers();
        }
    };
    $('#voyageNoBtn').click(function () {
        show_loading();
        $.post(rurl('declare/manifest/voyageNo'),{'msgType':$('#typeId').val()},function (res) {
           if(isSuccess(res)){
               $('#voyageNo').val(res.data);
               $('#voyageNoBtn').attr({'disabled':true}).addClass('layui-btn-disabled');
           }
        });
    });
    //提运单信息-表格选中监听
    table.on('row(mft-bill-tab)', function(obj){
        var checked = tabCheckboxChoice(obj,'mft-bill-list');
        if(checked){
            form.val('mftBillForm',obj.data);
            $('#billNo').select();
        }else{
            $('#newBill').click();
        }
        transLocationId();

        //重新加载商品项信息
        mftUtil.renderGoods();
        //清空商品项信息表单
        $('#mftGoodForm').find('input').val('');
        //重新加载集装箱信息
        mftUtil.renderContainers();
        //清空集装箱信息表单
        $('#mftContainerForm').find('input').val('');
    });
    //提运单信息-新增
    $('#newBill').click(function () {
        $('#mftBillForm').find('input').val('');
        $('#billNo').focus();
        transLocationId();
    });
    //提运单信息-复制
    $('#copyBill').click(function () {
        var selectData = table.checkStatus('mft-bill-list').data;
        if (selectData.length == 0) {show_msg('请选择一条您要复制的提运单信息');return;}
        if (selectData.length > 1) {show_msg('只能选择一条您要复制提运单信息');return;}
        $.each(mftUtil.data.mftBills,function (i,o) {
            o['LAY_CHECKED'] = false;
            o['LAY_TABLE_INDEX'] = i;
            o['listNo'] = (i+1);
        });
        var itemData = selectData[0];
        itemData['listNo'] = mftUtil.data.mftBills.length + 1;
        itemData['LAY_CHECKED'] = true;
        itemData['billNo'] = '';
        mftUtil.data.mftBills.push(itemData);
        mftUtil.renderBills(false);
        form.val('mftBillForm',itemData);
        $('#billNo').select();
        transLocationId();
    });
    //提运单信息-删除
    $('#delBill').click(function () {
        var selectData = table.checkStatus('mft-bill-list').data;
        if(selectData.length==0){show_msg('请至少选择一条您要删除的提运单信息');return;}
        confirm_inquiry('您确定要删除所选提运单信息？',function () {
            var newList = [];
            var removeGoodsIdList = [];//需要删除的商品项集合
            var removeContainerIdList = [];//需要删除的集装箱项集合
            $.each(table.cache["mft-bill-list"],function (i,o) {
                if(!o["LAY_CHECKED"]){
                    newList.push(o);
                } else {
                    //删除商品项信息和集装箱信息
                    $.each(table.cache["mft-good-list"],function (i,o2) {
                        if(isNotEmpty(o.billNo) && typeof o2.billNo != 'undefined' && o2.billNo == o.billNo){
                            table.cache["mft-good-list"].splice(i,1);
                            removeGoodsIdList.push(o2.id);
                        }
                    });
                    $.each(table.cache["mft-container-list"],function (i,o2) {
                        if(isNotEmpty(o.billNo) && typeof o2.billNo != 'undefined' && o2.billNo == o.billNo){
                            table.cache["mft-container-list"].splice(i,1);
                            removeContainerIdList.push(o2.id);
                        }
                    });
                }
            });
            mftUtil.data.mftBills = newList;
            mftUtil.renderBills(true);
            var newGoodsList = [];
            $.each(mftUtil.data.mftGoods,function (i,o) {
                if(!contain(removeGoodsIdList,o.id)){
                    newGoodsList.push(o);
                }
            });
            var newContainerList = [];
            $.each(mftUtil.data.mftContainers,function (i,o) {
                if(!contain(removeContainerIdList,o.id)){
                    newContainerList.push(o);
                }
            });
            mftUtil.data.mftGoods = newGoodsList;
            mftUtil.renderGoods();
            mftUtil.data.mftContainers = newContainerList;
            mftUtil.renderContainers();
            $('#newBill').click();
        });
    });
    //提运单信息-保存
    $('#saveBill').click(function () {
        var mftBillForm = $('#mftBillForm').find('.required').filter(':visible').not('.disabled');
        for(var i=0;i<mftBillForm.length;i++){
            var $that = $(mftBillForm[i]);
            if(isEmpty($that.val())){
                tipsMessage('必填项不能为空',$that);$that.focus();return;
            }
        }
        var rowData = $('#mftBillForm').serializeJson();
        //验证提(运)单号不能重复
        for(var i=0;i<mftUtil.data.mftBills.length;i++){
            var item = mftUtil.data.mftBills[i];
            if(isNotEmpty(item.billNo)&&item.listNo!=rowData.listNo&&item.billNo==rowData.billNo){
                tipsMessage('提(运)单号【'+rowData.billNo+'】已经存在',$('#billNo'));$('#billNo').select();return;
            }
        }
        if(isEmpty(rowData.listNo)){
            mftUtil.data.mftBills.push(rowData);
        }else{
            var newList = [];
            $.each(mftUtil.data.mftBills,function (i,o) {
               if(rowData.listNo==o.listNo){
                   if(rowData.billNo!=o.billNo){
                       $.each(mftUtil.data.mftGoods,function (j,k) {
                           if(o.billNo==k.billNo){k.billNo = rowData.billNo;}
                       });
                       $.each(mftUtil.data.mftContainers,function (j,k) {
                           if(o.billNo==k.billNo){k.billNo = rowData.billNo;}
                       });
                   }
                   newList.push(rowData);
               }else{
                   newList.push(o);
               }
            });
            mftUtil.data.mftBills = newList;
        }
        mftUtil.renderBills(true);
        $('#newBill').click();
    });
    //商品项信息-发货人回车事件
    $('#consignorName').enter(function () {
        $('#saveBill').click();
    });
    //---------------------------------------
    //商品项信息-表格选中监听
    table.on('row(mft-good-tab)', function(obj){
        var checked = tabCheckboxChoice(obj,'mft-good-list');
        if(checked){
            form.val('mftGoodForm',obj.data);
            $('#goodsPackNum').select();
        }else{
            $('#newGood').click();
        }
    });
    //商品项信息-新增
    $('#newGood').click(function () {
        $('#mftGoodForm').find('input').val('');
        $('#goodsPackNum').focus();
    });
    //商品项信息-复制
    $('#copyGood').click(function () {
        var selectData = table.checkStatus('mft-good-list').data;
        if (selectData.length == 0) {show_msg('请选择一条您要复制的商品项信息');return;}
        if (selectData.length > 1) {show_msg('只能选择一条您要复制商品项信息');return;}
        $.each(mftUtil.data.mftGoods,function (i,o) {
            o['LAY_CHECKED'] = false;
            o['LAY_TABLE_INDEX'] = i;
        });
        var itemData = selectData[0];
        itemData['id'] = uuid();
        itemData['LAY_CHECKED'] = true;
        mftUtil.data.mftGoods.push(itemData);
        mftUtil.renderGoods();
        form.val('mftGoodForm',itemData);
        $('#goodsPackNum').select();
    });
    //商品项信息-删除
    $('#delGood').click(function () {
        var selectData = table.checkStatus('mft-good-list').data;
        if(selectData.length==0){show_msg('请至少选择一条您要删除的商品项信息');return;}
        confirm_inquiry('您确定要删除所选商品项信息？',function () {
            var idList = [];
            $.each(table.cache["mft-good-list"],function (i,o) {
                if(o["LAY_CHECKED"]){
                    idList.push(o.id);
                }
            });
            var newList = [];
            $.each(mftUtil.data.mftGoods,function (i,o) {
                if(!contain(idList,o.id)){
                    newList.push(o);
                }
            });
            mftUtil.data.mftGoods = newList;
            mftUtil.renderGoods();
            $('#newGood').click();
        });
    });
    //商品项信息-保存
    $('#saveGood').click(function () {
        var $billNo = $('#billNo');
        if(isEmpty($billNo.val())){
            tipsMessage('提(运)单号不能为空',$billNo);$billNo.focus();return;
        }
        var mftGoodForm = $('#mftGoodForm').find('.required').filter(':visible').not('.disabled');
        for(var i=0;i<mftGoodForm.length;i++){
            var $that = $(mftGoodForm[i]);
            if(isEmpty($that.val())){
                tipsMessage('必填项不能为空',$that);$that.focus();return;
            }
        }
        var rowData = $('#mftGoodForm').serializeJson();
        rowData['billNo'] = $billNo.val();
        if(isEmpty(rowData.id)){
            rowData.id = uuid();
            mftUtil.data.mftGoods.push(rowData);
        }else{
            var newList = [];
            $.each(mftUtil.data.mftGoods,function (i,o) {
                if(rowData.id==o.id){
                    newList.push(rowData);
                }else{
                    newList.push(o);
                }
            });
            mftUtil.data.mftGoods = newList;
        }
        mftUtil.renderGoods();
        $('#newGood').click();
    });
    //商品项信息-发货人回车事件
    $('#goodsDetailDesc').enter(function () {
        $('#saveGood').click();
    });

    //---------------------------------------
    //集装箱信息-表格选中监听
    table.on('row(mft-container-tab)', function(obj){
        var checked = tabCheckboxChoice(obj,'mft-container-list');
        if(checked){
            form.val('mftContainerForm',obj.data);
            $('#contaId').select();
        }else{
            $('#newContainer').click();
        }
    });
    //集装箱信息-新增
    $('#newContainer').click(function () {
        $('#mftContainerForm').find('input').val('');
        $('#contaId').focus();
    });
    //集装箱信息-复制
    $('#copyContainer').click(function () {
        var selectData = table.checkStatus('mft-container-list').data;
        if (selectData.length == 0) {show_msg('请选择一条您要复制的集装箱信息');return;}
        if (selectData.length > 1) {show_msg('只能选择一条您要复制集装箱信息');return;}
        $.each(mftUtil.data.mftContainers,function (i,o) {
            o['LAY_CHECKED'] = false;
            o['LAY_TABLE_INDEX'] = i;
        });
        var itemData = selectData[0];
        itemData['id'] = uuid();
        itemData['LAY_CHECKED'] = true;
        mftUtil.data.mftContainers.push(itemData);
        mftUtil.renderContainers();
        form.val('mftContainerForm',itemData);
        $('#contaId').select();
    });
    //集装箱信息-删除
    $('#delContainer').click(function () {
        var selectData = table.checkStatus('mft-container-list').data;
        if(selectData.length==0){show_msg('请至少选择一条您要删除的集装箱信息');return;}
        confirm_inquiry('您确定要删除所选集装箱信息？',function () {
            var idList = [];
            $.each(table.cache["mft-container-list"],function (i,o) {
                if(o["LAY_CHECKED"]){
                    idList.push(o.id);
                }
            });
            var newList = [];
            $.each(mftUtil.data.mftContainers,function (i,o) {
                if(!contain(idList,o.id)){
                    newList.push(o);
                }
            });
            mftUtil.data.mftContainers = newList;
            mftUtil.renderContainers();
            $('#newContainer').click();
        });
    });
    //集装箱信息-保存
    $('#saveContainer').click(function () {
        var $billNo = $('#billNo');
        if(isEmpty($billNo.val())){
            tipsMessage('提(运)单号不能为空',$billNo);$billNo.focus();return;
        }
        var mftContainerForm = $('#mftContainerForm').find('.required').filter(':visible').not('.disabled');
        for(var i=0;i<mftContainerForm.length;i++){
            var $that = $(mftContainerForm[i]);
            if(isEmpty($that.val())){
                tipsMessage('必填项不能为空',$that);$that.focus();return;
            }
        }
        var rowData = $('#mftContainerForm').serializeJson();
        rowData['billNo'] = $billNo.val();
        if(isEmpty(rowData.id)){
            rowData.id = uuid();
            mftUtil.data.mftContainers.push(rowData);
        }else{
            var newList = [];
            $.each(mftUtil.data.mftContainers,function (i,o) {
                if(rowData.id==o.id){
                    newList.push(rowData);
                }else{
                    newList.push(o);
                }
            });
            mftUtil.data.mftContainers = newList;
        }
        mftUtil.renderContainers();
        $('#newContainer').click();
    });
    //集装箱信息-发货人回车事件
    $('#contaId').enter(function () {
        $('#saveContainer').click();
    });

    //查看回执
    $('#decReceipt').click(function () {
        var id = $('#mtfHeadForm #id').val();
        if(isEmpty(id)){show_msg('还未发送单一窗口');return;}
        openwin(rurl('declare/status/single-list.html?domainType=mainfest&domainId='+id),null,{
            area:['360px','520px'],shadeClose:true
        });
    });

    exports('mftUtil', mftUtil);
});